package com.brand.data.util;

import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 获取token类
 */
public class BaiduService {
	
	public static String access_token = "24.ba172ac1a408698c6048f2bd4673f905.2592000.1514251057.282335-10439097";
	public static final String BAIDU_AUTH_HOST = "https://aip.baidubce.com/oauth/2.0/token";
	private static final String BAIDU_VALID_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
	//百度云官网注册的api key
	public static final String CLIENT_ID = "5yKeM2cGlGyPCjg9U73jjmVQ";
	//官网获取的 Secret Key
	public static final String CLIENT_SECRET = "ezh3iRlApzKk2Gin0ld5EuBjMqmv21Gu";
	public static void getAuth() {
		access_token = getAuth(CLIENT_ID,CLIENT_SECRET);//
	}
	
    /**
     * 获取API访问token
     * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
     * @param ak - 百度云官网获取的 API Key
     * @param sk - 百度云官网获取的 Securet Key
     * @return assess_token 示例：
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
    	Connection conn = Jsoup.connect(BAIDU_AUTH_HOST).ignoreContentType(true)
    		.data("grant_type", "client_credentials")
    		.data("client_id", ak)
    		.data("client_secret", sk);
    	
        try {
        	Response response = conn.execute();
        	Map<String, String> headers = response.headers();
            String result = response.body();
            JSONObject jsonObject = JSON.parseObject(result);
            return jsonObject.getString("access_token");
        } catch (Exception e) {
            System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }
    /**
	 *传给百度进行图片识别 
	 */
	public static String validate(String base64img){
		try {
			Connection conn = Jsoup.connect(BAIDU_VALID_URL)
					   .validateTLSCertificates(false)
					   .ignoreContentType(true)
					   .header("Content-Type", "application/x-www-form-urlencoded");
			
			conn.data("image", base64img).data("access_token", access_token);
			conn.post();
			
			String body = new String(conn.response().bodyAsBytes(), "GBK");
			System.out.println("百度识别结果: "+body);
			
			JSONObject result = JSON.parseObject(body);
			////{"error_msg":"Access token invalid or no longer valid","error_code":110}
			if(result == null || result.containsKey("error_code")){
				BaiduService.getAuth();
				validate(base64img);
				return "error";
			}
			return result.getJSONArray("words_result").getJSONObject(0).getString("words");
		} catch (Exception e) {
			return null;
		}
	}
	public static String validate(byte[] imgByte){
	   return validate(Base64.encodeBase64String(imgByte));
	}
}